import { ref, computed, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { useDeptStore } from '@/stores/system/dept'
import type { ExtendedDept } from '@/types/api/system/dept'
import { storeToRefs } from 'pinia'

/**
 * 部门管理钩子函数
 */
export default function useDeptManagement() {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 使用状态管理 ------------
  const deptStore = useDeptStore()
  const { 
    loading, 
    submitLoading,
    deptList, 
    deptTreeData,
    expandedKeys,
    isExpandAll,
    modalVisible,
    queryParams,
    form,
    formMode,
    currentId
  } = storeToRefs(deptStore)
  
  // ------------ 组件引用 ------------
  const formRef = ref<FormInstance>()
  
  // ------------ 错误处理状态 ------------
  const loadError = ref(false)
  const errorMessage = ref('')
  
  // ------------ 计算属性 ------------
  const formTitle = computed(() => formMode.value === 'add' ? t('dept.add') : t('dept.edit'))
  
  // ------------ 树操作方法 ------------
  /**
   * 获取所有可展开的节点ID
   */
  const getExpandKeys = (list: ExtendedDept[]): string[] => {
    const keys: string[] = []
    const traverse = (items: ExtendedDept[]) => {
      items.forEach(item => {
        if (item.children && item.children.length > 0) {
          keys.push(item.id)
          traverse(item.children)
        }
      })
    }
    traverse(list)
    return keys
  }
  
  /**
   * 监听展开行变化
   */
  const onExpandedRowsChange = (keys: string[]) => {
    expandedKeys.value = keys
    isExpandAll.value = keys.length === getExpandKeys(deptList.value).length
  }
  
  /**
   * 展开/折叠所有
   */
  const handleExpandAll = () => {
    const keys = isExpandAll.value ? [] : getExpandKeys(deptList.value)
    expandedKeys.value = keys
    isExpandAll.value = !isExpandAll.value
  }
  
  // ------------ 搜索区域方法 ------------
  /**
   * 点击搜索
   */
  const handleSearch = () => {
    fetchDeptList()
  }
  
  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    queryParams.value.name = ''
    queryParams.value.status = undefined
    fetchDeptList()
  }
  
  // ------------ 数据获取方法 ------------
  /**
   * 获取部门列表
   */
  const fetchDeptList = async () => {
    try {
      // 重置错误状态
      loadError.value = false
      errorMessage.value = ''
      
      await deptStore.fetchDeptList()
      
      // 检查数据是否为空
      if (deptList.value.length === 0) {
        errorMessage.value = t('dept.emptyData')
      }
      
      return deptList.value
    } catch (error: any) {
      loadError.value = true
      errorMessage.value = error?.message || t('dept.loadFailed')
      return Promise.reject(error)
    }
  }
  
  // ------------ 状态操作方法 ------------
  /**
   * 切换部门状态
   */
  const handleStatusChange = async (dept: ExtendedDept, checked: boolean) => {
    if (dept.statusLoading) return
    
    try {
      dept.statusLoading = true
      const status = checked ? 1 : 0
      await deptStore.changeDeptStatusAction(dept.id, status)
      dept.status = status
    } catch (error) {
      dept.status = checked ? 0 : 1
    } finally {
      dept.statusLoading = false
    }
  }
  
  // ------------ 表单操作方法 ------------
  /**
   * 添加部门
   */
  const handleAdd = () => {
    formMode.value = 'add'
    deptStore.resetForm()
    form.value.parentId = '0'
    modalVisible.value = true
  }
  
  /**
   * 添加子部门
   */
  const handleAddSub = (dept: ExtendedDept) => {
    formMode.value = 'add'
    deptStore.resetForm()
    form.value.parentId = dept.id
    modalVisible.value = true
  }
  
  /**
   * 编辑部门
   */
  const handleEdit = (dept: ExtendedDept) => {
    formMode.value = 'edit'
    currentId.value = dept.id
    Object.assign(form.value, dept)
    modalVisible.value = true
  }
  
  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    await formRef.value?.validate()
    await deptStore.submitForm()
  }
  
  // ------------ 删除操作方法 ------------
  /**
   * 删除部门
   */
  const handleDelete = (dept: ExtendedDept) => {
    // 检查是否有子部门
    if (dept.children && dept.children.length > 0) {
      message.warning(t('dept.hasChildrenCannotDelete'))
      return
    }
  
    // 检查是否有用户
    if (dept.userCount && dept.userCount > 0) {
      message.warning(t('dept.hasUsersCannotDelete'))
      return
    }
    
    Modal.confirm({
      title: t('dept.confirmDelete'),
      content: t('dept.confirmDeleteContent', { name: dept.name }),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        await deptStore.removeDept(dept.id)
      }
    })
  }
  
  // ------------ 监听器 ------------
  watch(() => modalVisible.value, (val) => {
    if (!val) {
      // 弹窗关闭时重置表单
      deptStore.resetForm()
    }
  })
  
  // ------------ 初始化 ------------
  fetchDeptList()
  
  return {
    // 状态
    loading,
    submitLoading,
    deptList,
    deptTreeData,
    expandedKeys,
    isExpandAll,
    modalVisible,
    queryParams,
    form,
    formMode,
    formRef,
    formTitle,
    currentId,
    loadError,
    errorMessage,
    
    // 方法
    onExpandedRowsChange,
    handleSearch,
    handleReset,
    handleExpandAll,
    handleStatusChange,
    handleAdd,
    handleAddSub,
    handleEdit,
    handleDelete,
    handleSubmit,
    fetchDeptList
  }
} 